import fs from 'fs';
import { error, Ora } from '@/util';
import { BasePath } from '@/constant';
import path from 'path';
import { checkConfig, combineConfigs } from './check';

function check () {
    let ora = Ora('check config.json');
    const jsonPath = `${process.cwd()}/wudongCli.config.json`;
    const templateJSON = require(path.resolve(__dirname, BasePath.Default));
    const json = fs.existsSync(jsonPath) ? require(jsonPath) : templateJSON;

    ora.start()

    if (!fs.existsSync(jsonPath)) {
        error('Could not find wudongCli.config.json, please run "wudong-cli init" firstly...');
        return ora.fail();
    }
    /** 合并模板 json 与 custom json */
    const combinedJSON = fs.existsSync(jsonPath) ? combineConfigs(json, templateJSON) : templateJSON;
    /** 校验配置文件 */
    try {
        checkConfig(combinedJSON?.database || {});
        ora.succeed();
        return combinedJSON;
    } catch(e) {
        error(e as string);
        ora.fail();
        return null;
    }
};

export { 
    check,
}